
import React, { useState } from 'react'
import { useStore } from 'react-redux';
import { OrderGoodsItem } from '@common/goodsItem'
import { Toast, Modal } from 'antd-mobile';
import { handelDjOrder, entryGroup } from '@api/order';
import { detactGroupIsFull, _payTheBalance } from '@api/submit';
import { useHistory, } from 'react-router-dom';
import styled from 'styled-components'
import ReactDOM from 'react-dom'
import { updateOrder } from '../../../store/actionCreators';


const alert = Modal.alert

const OrderButton = (props) => {
  return (
    <button
      onClick={e => { props.click(e) }}
      style={{
        width: '2.06rem',
        // height: 'calc( 0.66rem * 10 / 10 )',
        padding: '.15rem 0',
        background: 'white',
        borderRadius: '.75rem',
        lineHeight: '1',
        textAlign: 'center',
        color: `#474747`,
        border: `solid 1px #474747`,
        fontSize: '.32rem',
        marginLeft: '.26rem'
      }}
    >
      {props.text}
    </button>
  )
}



const JianTong = (props) => {
  return (
    ReactDOM.createPortal(
      props.children,
      document.getElementById('jiantong')
    )
  )
}

const OrderItem = (props) => {
  const { item } = props

  const store = useStore();

  const { isApplet } = store.getState().appConfig
  const [showModal, setShowModal] = useState(false)
  const [isShareArray, setIsShareArray] = useState(false)


  // console.log(item.groupstatus, '团状态', typeof item.groupstatus)

  let history = useHistory();

  return (
    <>
      <div className="order-item " onClick={e => {
        isApplet ? window.navigateToWebWiew('purchaseOrderDetail/' + item.deposit_orderno) :
          history.push(`/purchaseOrderDetail/${item.deposit_orderno}`)
      }}>
        <div className="item-top flex-row">

          <p className="orderno flex-row">{item.deposit_orderno}
            {item.tuan_first === '1' && <img
              style={{
                width: '.95rem',
                height: '.35rem'
              }}
              src="https://res.lexiangpingou.cn/images/826/2020/11/I3yDS60Y4304osL03k3XslM3151WkF.png" alt="" />}
          </p>


          <p className="order-status">
            {/* {item.status === "1" && '待分享'} */}
            {item.status === "1" && item.groupstatus === "1" && '团失败'}
            {item.status === "1" && item.groupstatus === "2" && '团成功'}
            {item.status === "1" && item.groupstatus === "3" && '待分享'}
            {item.status === "2" && '拼货中'}
            {item.status === "4" && '拼车成功'}
            {item.status === "5" && '拼车失败'}
            {item.status === "3" && '拼车中'}
            {item.status === "11" && '已取消'}
            {item.status === "10" && '已退款'}
            {item.status === "-1" && '待支付保证金'}
            {/* 3 自己已付款，等待队友付款  */}
          </p>
        </div>
        <div className="line"></div>
        <div className="item-goods">
          <OrderGoodsItem marginStyle={{ marginTop: '.32rem' }} goods={item.good} />
          <div className="item-goods-bottom">
            <div className="totalprice" style={{ marginTop: '.32rem' }}>
              总价￥{item.good.price}
            </div>
          </div>
        </div>
        <div className="line"></div>
        <div className="item-option flex-row">
          {/* 不同转态不同按钮 */}

          {/* <div style={{ border: ' solid red 1px', height: '.8rem', alignItems: 'center', justifyContent: 'center', borderRadius: '.15rem' }} className="flex-column">
              <span>
                ===中中===
              </span>
          </div> */}

          {item.status === '-1' && <OrderButton text="支付保证金" click={e => { purchaseOrderHandle(e, item, 'pay_dj') }} />}
          {item.status === '2' && <OrderButton text="支付尾款" click={e => { purchaseOrderHandle(e, item, 'banlancePayment') }} />}
          {item.status === '-1' && <OrderButton click={e => { purchaseOrderHandle(e, item.deposit_orderno, 'cancel_djorder') }} text="取消订单" />}
          {item.status === '11' && <OrderButton click={e => { purchaseOrderHandle(e, item.deposit_orderno, 'delete_order') }} text="删除订单" />}

          {item.status === '1' && item.groupstatus === null && <OrderButton click={e => { purchaseOrderHandle(e, item.deposit_orderno, 'see_order') }} text="查看详情" />}

          {item.status === '1' && item.groupstatus && <OrderButton click={e => { purchaseOrderHandle(e, item.tuan_id, 'see_tuan') }} text="我的团" />}

          {(item.status === '1' && item.is_confirm === 1) && item.tuan_first === '1' && item.groupstatus === '3' && <OrderButton click={e => { purchaseOrderHandle(e, item.tuan_id, 'group_order') }} text="确认拼车" />}
          {(item.status === '1' && item.groupstatus === '3') && <OrderButton click={e => { purchaseOrderHandle(e, item.tuan_id, 'group_share') }} text="分享团" />}

          {item.status === '4' && <OrderButton click={e => { purchaseOrderHandle(e, item.deposit_orderno, 'see_order') }} text="查看订单" />}
          {item.status === '10' && <OrderButton click={e => { purchaseOrderHandle(e, item.deposit_orderno, 'see_order') }} text="查看订单" />}
        </div>
      </div>

      { isShareArray && <JianTong>
        <img style={{
          position: 'absolute',
          right: '15%',
        }}
          src="https://res.lexiangpingou.cn/images/826/2020/11/C570r7gQhDqRQBHB607h5K7HN5ZE5B.png" alt="" />
      </JianTong>}

      <Modal
        visible={showModal}
        onClose={e => {
          setShowModal(false)
          setIsShareArray(false)
        }}
        maskClosable={true}
        transparent
        popup={true}
        animationType='slide-up'
        style={{
          backgroundColor: 'white',
          borderRadius: '0px'
        }}

      >

        <ShareTypeStyle className="flex-row">
          <div className="item" onClick={e => { history.push('/sharegroup/' + item.tuan_id) }}>
            <img src="https://res.lexiangpingou.cn/images/vip/share3.png" alt="" />
            <p>生成图片</p>
          </div>
          <div className="item">
            <img src="https://res.lexiangpingou.cn/images/vip/share2.png" alt=""
              onClick={e => { setIsShareArray(!isShareArray) }}
            />
            <p>小程序分享</p>
          </div>
        </ShareTypeStyle>
      </Modal>

    </>
  );


  function purchaseOrderHandle(e, orderParams, handel) {
    e.stopPropagation();

    let params = {
      action: handel,
      deposit_orderno: orderParams
    }

    const { good, price_validity, deposit_orderno, needprepayprice, sfje: realPrice, tuan_id, needprepayratio, orderno } = orderParams
    const uniacid = store.getState().appConfig.uniacid

    switch (handel) {
      case 'delete_order':
        handelDjOrder(params).then(res => {
          if (res.status === 200) {
            Toast.success(res.msg, 1)
            props.deleteOrder()
          }
          else { Toast.fail(res.msg, 1) }
        })
        break;
      case 'cancel_djorder':

        alert('确定要取消订单吗？', '', [
          {
            text: '取消', onPress: () => {
              console.log(params)
            }
          },
          {
            text: '确认', onPress: () => {
              handelDjOrder(params).then(res => { if (res.status === 200) { Toast.success(res.msg); window.location.reload() } else { Toast.fail(res.msg) } })
            }
          },
        ])

        break;

      case 'banlancePayment':
        // 支付尾款

        store.dispatch(updateOrder(Object.assign({}, store.getState().order, {
          orderno: orderno, tuanid: tuan_id, needprepayprice, needprepayratio, realPrice, uniacid, good
        })))

        isApplet ? window.navigateToWebWiew(`/payway/${deposit_orderno}`) : history.push(`/payway/${deposit_orderno}`)

        break;
      case 'pay_dj':
        // 支付保证金
        // const { good, price_validity, deposit_orderno, needprepayprice, sfje: realPrice, tuan_id, needprepayratio } = orderParams

        const validity = parseInt(price_validity) * 1000
        const now = parseInt(new Date().getTime())
        if (now > validity) { // 判断商品供应价是否过期
          Toast.info('该商品供应价已过期', 2)
          return
        }

        if (tuan_id !== "0") {  // 参团得人
          detactGroupIsFull({ tuan_id }).then(res => {
            if (res.status === 200) {
              const needNum = parseInt(good.num)
              const haveNum = parseInt(res.data)
              if (needNum > haveNum) {
                Toast.info('所购数量超出先有库存', 2)
              } else {
                store.dispatch(updateOrder(Object.assign({}, store.getState().order, {
                  orderno: deposit_orderno, tuanid: tuan_id, needprepayprice, needprepayratio, realPrice, uniacid, good
                })))
                isApplet ? window.navigateToWebWiew(`/payway/${deposit_orderno}`) : history.push(`/payway/${deposit_orderno}`)

              }
            } else {
              Toast.info('未知错误(1004)', 1)
            }
          })
        } else { // 开团得人没有tuanid
          console.log('don\'t detact')

          store.dispatch(updateOrder(Object.assign({}, store.getState().order, {
            orderno: deposit_orderno, tuanid: tuan_id, needprepayprice, needprepayratio, realPrice, uniacid, good
          })))
          isApplet ? window.navigateToWebWiew(`/payway/${deposit_orderno}`) : history.push(`/payway/${deposit_orderno}`)
        }
        break;

      case 'group_order':
        // 确认成团
        alert('该车还未满载，确认要拼车吗', '', [
          {
            text: '取消', onPress: () => {
              console.log(params)
            }
          },
          {
            text: '确认', onPress: () => {
              entryGroup({ tuan_id: orderParams }).then(res => {
                console.log(res)
                if (res.status === 200) {
                  Toast.info(res.msg, 1)
                  window.location.reload()
                } else {
                  Toast.info(res.msg, 1)
                }
              })
            }
          },
        ])
        break;
      case 'see_tuan':
        // 查看我的团
        isApplet ? window.navigateToWebWiew('/group/' + orderParams) : history.push('/group/' + orderParams)
        break;
      case 'group_share':
        history.push('/sharegroup/' + orderParams)
        // setShowModal(!showModal)
        break;

      default:
        isApplet ? window.navigateToWebWiew(`/purchaseOrderDetail/${orderParams}`) : history.push(`/purchaseOrderDetail/${orderParams}`)
        console.log('查看订单')
        break;
    }
  }
}

export default OrderItem;

const ShareTypeStyle = styled.div`
  flex: 1 1 0%;
  justify-content: space-around;
  .item{
  img{
    width: 1.49rem;
    height: 1.49rem;
  }
}

.share-array{
  position: absolute;
  width: 100%;
  height: 100vh;
  background-color: rgba(34, 40, 54, 0.2);
  top: 0;
  text-align: right;
  img{
    margin-right: .4rem;
  }

    }

`